package com.yenlien.traceyun.webase.utils;

import com.yenlien.traceyun.common.utils.LoggerUtil;
import org.springframework.util.StringUtils;

import javax.persistence.Table;
import java.lang.reflect.Field;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-06-19
 * @description:
 **/
public class CommonUtil {

    /**
     * 获取表名
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> String getTableName(Class<T> clazz) {
        if (clazz.isAnnotationPresent(Table.class)) {
            Table table = clazz.getDeclaredAnnotation(Table.class);
            String name = table.name();
            if (StringUtils.isEmpty(name)) {
                return clazz.getSimpleName();
            } else {
                return name;
            }
        }
        return clazz.getSimpleName();
    }

    public static <T> T parse(Class<T> tClass, Object[] objects, String[] strings) {
        try {
            T obj = tClass.newInstance();
            if (strings != null && strings.length > 0) {
                Field[] fields = tClass.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    for (int i = 0; i < strings.length; i++) {
                        if (field.getName().toLowerCase().equals(strings[i].replaceAll("_", ""))) {
                            field.set(obj, objects[i]);
                            break;
                        }
                    }
                }
                Field[] superfields = tClass.getSuperclass().getDeclaredFields();
                for (Field field : superfields) {
                    field.setAccessible(true);
                    for (int i = 0; i < strings.length; i++) {
                        if (field.getName().toLowerCase().equals(strings[i].replaceAll("_", ""))) {
                            field.set(obj, objects[i]);
                            break;
                        }
                    }
                }
            }
            return obj;
        } catch (Exception e) {
            LoggerUtil.getLogger().error("CommonUtil->parse error :{}", e.getMessage());
        }
        return null;
    }
}
